// Copyright 2023 Huawei Cloud Computing Technology Co., Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef VMI_TCP_SERVER_SOCKET_H
#define VMI_TCP_SERVER_SOCKET_H

#include <thread>
#include "VmiTcpSocket.h"

class VmiTcpServerSocket : public VmiTcpSocket {
public:
    /*
     * @功能描述：TCP服务端套接字构造函数
     * @参数 [in] localIp：本地IP
     * @参数 [in] localPort：本地端口
     * @参数 [in] service：需要注册的新连接处理对象
     */
    VmiTcpServerSocket(unsigned int localIp, unsigned short int localPort,
        std::shared_ptr<VmiServerService> service);

    /*
     * @功能描述：TCP服务端套接字构造函数
     * @参数 [in] socketOption：socket选项
     * @参数 [in] localIp：本地IP
     * @参数 [in] localPort：本地端口
     * @参数 [in] service：需要注册的新连接处理对象
     */
    VmiTcpServerSocket(unsigned int socketOption, unsigned int localIp, unsigned short int localPort,
        std::shared_ptr<VmiServerService> service);

    /*
     * @功能描述：析构，关闭套接字，停止连接监听线程
     */
    ~VmiTcpServerSocket() override;

    /*
     * @功能描述：通知VmiServerService对象有新连接接入
     * @参数 [in] socket：新连接的VmiTcpSocket智能指针
     */
    void NotifyServerService(std::shared_ptr<VmiTcpSocket> socket);

    /*
     * @功能描述：获取监听状态
     * @返回值：监听状态
     */
    int GetListenStatus();

    /*
     * @功能描述：启动TCP服务端
     * @返回值：成功返回SOCK_RET_SUCCESS，失败返回SOCK_RET_FAILED
     */
    int Start();

    static const int MAX_LISTEN_NUM = 5;

private:
    volatile int m_listenStatus = 0;
    std::thread* m_acceptTask = nullptr;
    std::shared_ptr<VmiServerService> m_service = nullptr;

    /*
     * @功能描述：启动监听线程
     */
    int StartAcceptThread();
};

#endif // VMI_TCP_SERVER_SOCKET_H